/* 
 * shamefully copy from AnFetion.
 * more see: http://code.google.com/p/anfetion/
 */
package person.bangbang.im.Androidgin.Fetion;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import person.bangbang.im.Androidgin.Util.Log;

public final class SystemConfig extends FetionBase {
    public static final String SYSTEMCONFIGURL = "http://nav.fetion.com.cn/nav/getsystemconfig.aspx";
    public static final String SYSTEMCONFIGURL_ALT = "http://221.130.45.201/nav/getsystemconfig.aspx";
    private String sipcproxy_address;

    public String getSipcproxy_address() {
        return sipcproxy_address;
    }

    public void setSipcproxy_address(String sipcproxy_address) {
        this.sipcproxy_address = sipcproxy_address;
    }

    private int sipcproxy_port;

    public int getSipcproxy_port() {
        return sipcproxy_port;
    }

    public void setSipcproxy_port(int sipcproxy_port) {
        this.sipcproxy_port = sipcproxy_port;
    }

    private String ssiAppSigninUrl;

    public String getSsiAppSigninUrl() {
        return ssiAppSigninUrl;
    }

    public void setSsiAppSigninUrl(String ssiAppSigninUrl) {
        this.ssiAppSigninUrl = ssiAppSigninUrl;
    }

    private String mobileno;

    public String getMobileno() {
        return mobileno;
    }

    public SystemConfig(String mobileno) {
        this.mobileno = mobileno;
    }

    @Override
    public boolean execute() {
        return visit(SYSTEMCONFIGURL) || visit(SYSTEMCONFIGURL_ALT);
    }

    private boolean visit(String url) {
        // System.out.println(url);
        this.onStatusChanged(StatusDefine.EMPTY, StatusDefine.INITINGDATA);
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        post.addHeader("UserAgent", USERAGENT);
        post.addHeader("Content-type", CONTENTTYPE);
        String req = "<config><user mobile-no=\""
                + mobileno
                + "\"/><client "
                + CLIENT
                + " /><servers version=\"0\" /><service-no version=\"40\" /><parameters version=\"48\" /><hints version=\"42\" /><http-applications version=\"47\" /><client-config version=\"54\" /></config>";
        byte[] reqbuffer = req.getBytes();
        ByteArrayEntity entity = new ByteArrayEntity(reqbuffer);
        post.setEntity(entity);
        HttpResponse response;
        try {
            // System.out.println("start");
            response = client.execute(post);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                InputStream stream = response.getEntity().getContent();
                Header[] cl = response.getHeaders("content-length");
                String str = "";
                if (cl.length > 0) {
                    byte[] data = new byte[Integer.valueOf(cl[0].getValue())];
                    int count = stream.read(data);
                    while (count < data.length) {
                        int read = stream.read(data, count, data.length - count);
                        count += read > -1 ? read : 0;
                    }
                    str = new String(data);

                }
                stream.close();
                Document doc = parseXmlDocument(str);

                Element config = doc.getDocumentElement();
                if (config == null || !config.getNodeName().equals("config")) {
                    if (Settings.DEBUG) Log.d(SystemConfig.class.getSimpleName(),
                            "The config file gained error when ssiappsignin.");
                    if (Settings.DEBUG) Log.d(SystemConfig.class.getSimpleName(), str);
                    this.onSetText("The config file gained error when ssiappsignin.");
                    this.onStatusChanged(StatusDefine.GETINGSYSTEMCONFIG, StatusDefine.EMPTY);
                    return false;
                }
                NodeList serverNode = config.getElementsByTagName("servers");
                if (serverNode.getLength() != 1) {
                    if (Settings.DEBUG) Log.d(SystemConfig.class.getSimpleName(), "servers item error");
                    if (Settings.DEBUG) Log.d(SystemConfig.class.getSimpleName(), str);
                    this.onSetText("servers item error");
                    this.onStatusChanged(StatusDefine.GETINGSYSTEMCONFIG, StatusDefine.EMPTY);
                    return false;
                } else {
                    Element server = (Element) serverNode.item(0);
                    NodeList sipcproxyNode = server.getElementsByTagName("sipc-proxy");
                    if (sipcproxyNode.getLength() != 1) {
                        if (Settings.DEBUG) Log.d(SystemConfig.class.getSimpleName(),
                                "Can't find sipc-proxy segment.");
                        if (Settings.DEBUG) Log.d(SystemConfig.class.getSimpleName(), str);
                        this.onSetText("Can't find sipc-proxy segment.");
                        this.onStatusChanged(StatusDefine.GETINGSYSTEMCONFIG, StatusDefine.EMPTY);
                        return false;
                    } else {
                        String[] sipcproxy = sipcproxyNode.item(0).getFirstChild().getNodeValue().split(":");
                        if (sipcproxy.length != 2 || sipcproxy[0].equals("") || sipcproxy[1].equals("")) {
                            if (Settings.DEBUG) Log.d(SystemConfig.class.getSimpleName(),
                                    "sipc-proxy segment error:");
                            if (Settings.DEBUG) Log.d(SystemConfig.class.getSimpleName(), str);
                            this.onSetText("sipc-proxy segment error");
                            this.onStatusChanged(StatusDefine.GETINGSYSTEMCONFIG, StatusDefine.EMPTY);
                            return false;
                        } else {
                            this.setSipcproxy_address(sipcproxy[0]);
                            this.setSipcproxy_port(Integer.parseInt(sipcproxy[1]));
                        }
                    }

                    NodeList ssiAppSigninNode = server.getElementsByTagName("ssi-app-sign-in");
                    if (ssiAppSigninNode.getLength() != 1) {
                        if (Settings.DEBUG) Log.d(SystemConfig.class.getSimpleName(),
                                "Can't find sipc-proxy segment.");
                        if (Settings.DEBUG) Log.d(SystemConfig.class.getSimpleName(), str);
                        this.onSetText("Can't find sipc-proxy segment.");
                        this.onStatusChanged(StatusDefine.GETINGSYSTEMCONFIG, StatusDefine.EMPTY);
                        return false;
                    } else {
                        String ssiappsigninUrl = ssiAppSigninNode.item(0).getFirstChild().getNodeValue();
                        if (ssiappsigninUrl.equals("")) {
                            if (Settings.DEBUG) Log.d(SystemConfig.class.getSimpleName(),
                                    "ssi-app-sign-in segment error:");
                            if (Settings.DEBUG) Log.d(SystemConfig.class.getSimpleName(), str);
                            this.onSetText("ssi-app-sign-in segment error");
                            this.onStatusChanged(StatusDefine.GETINGSYSTEMCONFIG, StatusDefine.EMPTY);
                            return false;
                        } else {
                            this.setSsiAppSigninUrl(ssiappsigninUrl);
                        }
                    }
                    this.onSetText("Get config info OK.");
                    this.onStatusChanged(StatusDefine.GETINGSYSTEMCONFIG, StatusDefine.GETSYSTEMCONFIGOK);
                    return true;
                }
            } else {
                this.onSetText(response.getStatusLine().getReasonPhrase());
                this.onStatusChanged(StatusDefine.GETINGSYSTEMCONFIG, StatusDefine.EMPTY);
                return false;
            }
        } catch (ClientProtocolException e) {
            // System.out.println("here");
            e.printStackTrace();
            this.onSetText(e.getMessage());
            this.onStatusChanged(StatusDefine.GETINGSYSTEMCONFIG, StatusDefine.EMPTY);
            return false;

        } catch (IOException e) {
            // System.out.println("or here");
            e.printStackTrace();
            this.onSetText(e.getMessage());
            this.onStatusChanged(StatusDefine.GETINGSYSTEMCONFIG, StatusDefine.EMPTY);
            return false;
        }

    }
}
